package jjn.round2;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-05-13 17:06
 */
public class Offer34_PathSum {
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(root, result, new LinkedList<>(), target);
        return result;
    }
    
    private void dfs(TreeNode node, List<List<Integer>> result, LinkedList<Integer> path, int remain) {
        if (node == null) {
            return;
        }
        remain = remain - node.val;
        path.add(node.val);
        if (remain == 0 && node.left == null && node.right == null) {
            result.add(new ArrayList<>(path));
        } else {
            dfs(node.left, result, path, remain);
            dfs(node.right, result, path, remain);
        }
        path.removeLast();
    }
}
